import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../controller/wallet_controller.dart';

class WebViewPage extends StatefulWidget {
  final String url;
  final String title;

  const WebViewPage({
    Key? key,
    required this.url,
    required this.title,
  }) : super(key: key);

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  WebViewController? _controller;
  bool _isLoading = true;
  String _currentUrl = '';
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    // 确保WalletController已注册
    if (!Get.isRegistered<WalletController>()) {
      Get.put(WalletController());
    }
    _initializeWebView();
  }

  void _initializeWebView() {
    try {
      // 打印URL以便调试
      print('尝试加载URL: ${widget.url}');
      
      // 验证URL格式 - 移除严格验证，只要能解析就接受
      Uri uri;
      try {
        uri = Uri.parse(widget.url);
      } catch (e) {
        print('URL解析错误: $e');
        throw FormatException('URL解析错误: ${widget.url}');
      }
      
      _controller = WebViewController()
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..setBackgroundColor(const Color(0x00000000))
        ..setNavigationDelegate(
          NavigationDelegate(
            onProgress: (int progress) {
              // 更新加载进度
              print('加载进度: $progress%');
            },
            onPageStarted: (String url) {
              print('页面开始加载: $url');
              if (mounted) {
                setState(() {
                  _isLoading = true;
                  _currentUrl = url;
                });
              }
            },
            onPageFinished: (String url) {
              print('页面加载完成: $url');
              if (mounted) {
                setState(() {
                  _isLoading = false;
                  _currentUrl = url;
                });
              }
            },
            onWebResourceError: (WebResourceError error) {
              print('WebView错误: ${error.description}, 错误码: ${error.errorCode}');
              _hasError = true;
              Get.snackbar(
                'Tips',
                'Please check your network connection and try again.',
                backgroundColor: Color(0xFF2A2A2A),
                colorText: Colors.white,
              );
            },
          ),
        );
      
      // 安全地加载URL
      _controller?.loadRequest(uri);
    } catch (e) {
      // 处理URL解析错误
      _hasError = true;
      Get.snackbar(
        'Error',
        'Invalid URL format: ${widget.url}',
        backgroundColor: Color(0xFF2A2A2A),
        colorText: Colors.white,
      );
      // 延迟返回，让用户看到错误信息
      // 避免使用Get.back()，改用Navigator.pop()防止LateInitializationError
      Future.delayed(Duration(seconds: 2), () {
        if (mounted && Navigator.canPop(context)) {
          Navigator.pop(context);
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF1A1A1A),
      appBar: AppBar(
        backgroundColor: Color(0xFF2A2A2A),
        title: Text(
          widget.title,
          style: TextStyle(color: Colors.white),
        ),
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            print('返回按钮被点击');
            if (Navigator.canPop(context)) {
              Navigator.pop(context);
            } else {
              print('无法返回，没有上一级页面');
            }
          },
        ),
        actions: [
          if (_controller != null)
            IconButton(
              icon: Icon(Icons.refresh, color: Colors.white),
              onPressed: () => _controller?.reload(),
            ),
        ],
      ),
      body: Stack(
        children: [
          // 始终显示WebView，即使在加载中
          if (_controller != null)
            WebViewWidget(controller: _controller!),
          // 只在加载中或出错时显示加载指示器，但不覆盖整个WebView
          if (_isLoading && !_hasError)
            Container(
              color: Color(0xFF1A1A1A).withOpacity(0.5),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                    ),
                    SizedBox(height: 16),
                    Text(
                      'loading'.tr,
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
          // 只在出错或控制器为空时显示错误信息
          if (_hasError || _controller == null)
            Container(
              color: Color(0xFF1A1A1A),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.error_outline, color: Colors.red, size: 48),
                    SizedBox(height: 16),
                    Text(
                      'error'.tr,
                      style: TextStyle(color: Colors.white),
                    ),
                    SizedBox(height: 24),
                    ElevatedButton(
                      onPressed: () {
                        setState(() {
                          _hasError = false;
                        });
                        _initializeWebView();
                      },
                      child: Text('retry'.tr),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
}